﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MREO.data;
using System.Data.SqlServerCe;
using System.Diagnostics;

namespace MREO.gui
{
    public partial class fGroupDocObjects : Form
    {
        private fMain mainForm;

        supportMethod supMeth = new supportMethod();

        Connection Conn = new Connection();
        SqlCeDataAdapter adapter = new SqlCeDataAdapter();
        SqlCeCommand command = null;

        DataTable dtTemplate;

        /// <summary>
        /// Имя объекта отображаемого формой
        /// </summary>
        public string oName;

        docBaySell oDoc;

        public string tabKey;

        public fGroupDocObjects(string pTepeObject, Object pObject)
        {
            mainForm = MdiParent as fMain;
            oName = pTepeObject;

            switch (oName)
            {
                case "docBaySell":
                    oDoc = pObject as docBaySell;
                    break;
            }

            InitializeComponent();
        }

        private void fGroupDocObjects_Shown(object sender, EventArgs e)
        {
            propertyGrid_main.SelectedObject = oDoc;
        }

        private void button_createDoc_Click(object sender, EventArgs e)
        {
            tabControl_main.TabPages.Clear();

            switch (oName)
            {
                case "docBaySell":
                    docBaySell();
                    break;
            }
        }

        // Расматриваем ситуацию когда загруженно снятие с учета, постановка на учет и договор
        private void docBaySell()
        {
            // выбераем шабоны относящиеся к группе
            fullTemplate(0);

        }

        private void fullTemplate(int p)
        {
            TabPage tp;
            WebBrowser wb;
            ToolStrip ts;
            ToolStripButton tsb;

            // Выбераем шаблоны
            dtTemplate = new DataTable();
            try
            {
                Conn.con.Open();

                command = new SqlCeCommand("SELECT id, doc_type, doc_name, template, groupDoc FROM mnuItems WHERE groupDoc = @groupDoc"
                                            , Conn.con);
                command.Parameters.Add("@groupDoc", SqlDbType.Int).Value = p;
                adapter.SelectCommand = command;
                adapter.Fill(dtTemplate);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            finally
            {
                command.Dispose();
                adapter.Dispose();
                if (Conn.con.State == ConnectionState.Open)
                    Conn.con.Close();
            }
            
            // отображаем их табконтроле
            foreach(DataRow dr in dtTemplate.AsEnumerable())
            {
                // Создаем новую вкладку и добавляем в нее веб браузер с именем из id и doc_type шаблона
                tp = new TabPage(dr["doc_name"].ToString());
                wb = new WebBrowser();
                ts = new ToolStrip();

                tsb = new ToolStripButton();
                tsb.ToolTipText = "Печать";
                tsb.Image = global::MREO.gui.Properties.Resources.Printer;
                tsb.ImageTransparentColor = System.Drawing.Color.Magenta;
                tsb.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
                tsb.Click += new EventHandler(tsb_Click);

                ts.Dock = DockStyle.Top;
                ts.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
                ts.Items.Add(tsb);

                wb.Tag = dr["id"].ToString();
                wb.Dock = DockStyle.Fill;
                wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
                wb.DocumentText = Encoding.UTF8.GetString((byte[])dr["template"]);

                tp.Controls.Add(ts);
                tp.Controls.Add(wb);

                tabControl_main.TabPages.Add(tp);
            }
        }

        void tsb_Click(object sender, EventArgs e)
        {
            ToolStripButton tsb = sender as ToolStripButton;
            ToolStrip ts = tsb.GetCurrentParent();

            TabPage tPage = ts.Parent as TabPage;
            foreach (Control ctrl in tPage.Controls)
            {
                if (ctrl.GetType() == (new WebBrowser()).GetType())
                {

                    ((WebBrowser)ctrl).ShowPrintPreviewDialog();

                    try
                    {
                        supMeth.saveLogPrint(tPage.Text);
                    }
                    catch (Exception exc) { MessageBox.Show(exc.Message); }
                }
            }
        }

        void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser wb = sender as WebBrowser;
            // Применяем параметры к шаблону
            fullTemplateParameter(wb, int.Parse(wb.Tag.ToString()));
        }

        private void fullTemplateParameter(WebBrowser wb, int pTemplId)
        {

            DataTable dt = new DataTable();
            try
            {
                Conn.con.Open();

                command = new SqlCeCommand("SELECT xname, xvalue " +
                                            " FROM templateParam WHERE mnuItems = @mnuItems ORDER BY xname"
                                            , Conn.con);
                command.Parameters.Add("@mnuItems", SqlDbType.NVarChar).Value = pTemplId;
                adapter.SelectCommand = command;
                adapter.Fill(dt);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            finally
            {
                command.Dispose();
                adapter.Dispose();
                if (Conn.con.State == ConnectionState.Open)
                    Conn.con.Close();
            }

            // Вызваем методы заполняющие шаблон
            string xName;
            string xValue;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                xName = dt.Rows[i]["xvalue"].ToString();

                switch (xName.Substring(0, 1))
                {
                    case "#":       // Глобальный параметр
                        xName = xName.Substring(1, xName.Length - 1);
                        xValue = getGValParamValue(xName);
                        break;

                    case "!":       // Параметр группового заполнения
                        xName = xName.Substring(1, xName.Length - 1);
                        xValue = getGroupParamValue(xName);
                        break;

                    default:        // Простой параметр
                        xValue = xName;
                        break;
                }

                wb.Document.InvokeScript(dt.Rows[i]["xname"].ToString(), new object[] { xValue });
            }
        }

        // Параметр группового заполнения
        private string getGroupParamValue(string xName)
        {
            object oVal = oDoc.getValueByName(xName);
            Debug.Print(xName + " : " + (oVal == null ? string.Empty : oVal.ToString()));
            return oVal == null ? string.Empty : oVal.ToString();
        }

        // Глобальный параметр
        private string getGValParamValue(string xName)
        {
            string xvalue = xName; // Если не найдется параметр вернется имч указанного параметра
            DataTable dt = new DataTable();

            try
            {
                Conn.con.Open();

                command = new SqlCeCommand("SELECT xvalue " +
                                            " FROM gval WHERE xname = @xname"
                                            , Conn.con);
                command.Parameters.Add("@xname", SqlDbType.NVarChar).Value = xName;
                adapter.SelectCommand = command;
                adapter.Fill(dt);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            finally
            {
                command.Dispose();
                adapter.Dispose();
                if (Conn.con.State == ConnectionState.Open)
                    Conn.con.Close();
            }

            foreach (DataRow dr in dt.AsEnumerable())
            {
                xvalue = dr["xvalue"].ToString();
            }

            return xvalue;
        }

        private void button_clear_Click(object sender, EventArgs e)
        {

            switch (oName)
            {
                case "docBaySell":
                    oDoc = new docBaySell();
                    break;
            }

            propertyGrid_main.SelectedObject = oDoc;

        }
    }
}
